/*
 * @Description: 左键点击复制到剪贴板
 * @Author: HuiSir<273250950@qq.com>
 * @Date: 2022-03-02 16:14:44
 * @LastEditTime: 2025-08-04 18:53:49
 */
import { Directive, DirectiveBinding } from "vue";
import { ElMessage } from "element-plus";
import { copy2Clipboard } from "@/utils/common";
/* eslint-disable @typescript-eslint/no-explicit-any */

const copyVal: Record<number, string> = {};
const vCopy: Directive<HTMLElement, string> = {
  mounted(el: HTMLElement, binding: DirectiveBinding<string>, vnode: any) {
    // 使用uid区分相同元素多个指令
    copyVal[vnode.ctx.uid] = binding.value;
    el.onclick = async () => {
      try {
        const copyRes = await copy2Clipboard(copyVal[vnode.ctx.uid]);
        if (copyRes) {
          ElMessage({ type: "success", message: "已成功复制到剪贴板" });
        }
      } catch (error) {
        ElMessage({ type: "error", message: error as string });
      }
    };
  },
  updated(_, binding, vnode: any) {
    copyVal[vnode.ctx.uid] = binding.value;
  },
  beforeUnmount(el, _, vnode: any) {
    delete copyVal[vnode.ctx.uid];
    el.onclick = null;
  },
};

export default vCopy;
